package com.example.test.domain;

import com.example.test.converter.JsonConverter;
import com.example.test.domain.group.validation.Create;
import com.example.test.domain.group.validation.Update;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.core.GrantedAuthority;

import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.Entity;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

/**
 * 角色
 */
@EqualsAndHashCode(callSuper = true)
@Entity
@Data
public class Role extends Base implements Serializable, GrantedAuthority, ConfigAttribute {
    /**
     * 名称
     */
    @NotNull(groups = {Create.class, Update.class})
    private String name;

    /**
     * 角色代码
     */
    @NotNull(groups = {Create.class, Update.class})
    private String code;

    /**
     * 权限
     */
    @Convert(converter = AuthoritiesConverter.class)
    private Set<String> authorities;

    /**
     * 描述
     */
    @Column(name = "[describe]")
    private String describe;

    public void setCode(String code) {
        if(code.startsWith("ROLE_")) {
            this.code = code.toUpperCase();
        }else {
            this.code = "ROLE_" + code.toUpperCase();
        }
    }

    @Override
    public String getAuthority() {
        return code;
    }

    @Override
    public String getAttribute() {
        return code;
    }

    public static class AuthoritiesConverter extends JsonConverter<Set<String>>{
        @Override
        public Set<String> convertToEntityAttribute(String s) {
            try {
                return getObjectMapper().readValue(s, getObjectMapper().getTypeFactory().constructCollectionType(HashSet.class, String.class));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
